package com.hopu.v1.service.admin.exam.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.mapper.admin.classes.StudentMapper;
import com.hopu.v1.mapper.admin.exam.ExamRecordsMapper;
import com.hopu.v1.pojo.classes.Student;
import com.hopu.v1.pojo.exam.ExamOptionAnswer;
import com.hopu.v1.pojo.exam.ExamQuestions;
import com.hopu.v1.pojo.exam.ExamRecords;
import com.hopu.v1.pojo.exam.ExamStudentRecords;
import com.hopu.v1.service.admin.classes.StudentService;
import com.hopu.v1.service.admin.exam.ExamOptionAnswerService;
import com.hopu.v1.service.admin.exam.ExamQuestionsService;
import com.hopu.v1.service.admin.exam.ExamRecordsService;
import com.hopu.v1.service.front.exam.EStudentRecordsService;
import com.hopu.v1.vo.ExamStudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author lihao
* @description 针对表【exam_records(考试记录表)】的数据库操作Service实现
* @createDate 2024-09-24 16:40:51
*/
@Service
public class ExamRecordsServiceImpl extends ServiceImpl<ExamRecordsMapper, ExamRecords>
    implements ExamRecordsService {

    @Autowired
    protected ExamRecordsMapper examRecordsMapper;
    @Autowired
    private ExamQuestionsService examQuestionsService;
    @Autowired
    private ExamOptionAnswerService examOptionAnswerService;
    @Autowired
    private EStudentRecordsService eStudentRecordsService;
    @Autowired
    private StudentService studentService;
    /**
     * 新增试卷
     * @param examRecords
     */
    @Override
    public void add(ExamRecords examRecords) {
        examRecords.setCreateTime(LocalDateTime.now());
        if(examRecords.getExamStartTime().isBefore(LocalDateTime.now())){
            examRecords.setStatus(1);
        }
        save(examRecords);
    }

    /**
     * 新增试卷、题目、选项
     * @param examRecords
     */
    @Transactional
    @Override
    public void addExam(ExamRecords examRecords) {
        examRecords.setCreateTime(LocalDateTime.now());
        if(examRecords.getExamStartTime().isBefore(LocalDateTime.now())){
            examRecords.setStatus(1);
        }else {
            examRecords.setStatus(0);
        }
        save(examRecords);
        Integer examRecordId = examRecords.getId();
        // 批量插入题目
        System.out.println(examRecords);
        List<ExamQuestions> questions = examRecords.getList();
        for (ExamQuestions question : questions) {
            question.setExamRecordId(examRecordId);
        }
        examQuestionsService.batchAdd(questions);

        // 批量插入选项
        List<ExamOptionAnswer> allOptions = new ArrayList<>();
        for (ExamQuestions question : questions) {
            if(question.getQuestionType().equals("3")){
                if(question.getAnswerContent().isEmpty()){
                    throw new RuntimeException("主观题参考答案不能为空");
                }
            }
            if(question.getQuestionTitle().isEmpty()){
                throw new RuntimeException("题干内容不能为空");
            }else {
                if (question.getOptions() != null) {
                    for (ExamOptionAnswer option : question.getOptions()) {
                        if(!option.getOptionText().isEmpty()){
                            option.setQuestionId(question.getId());
                            allOptions.add(option);
                        }else {
                            throw new RuntimeException("选项内容不能为空");
                        }
                    }
                }
            }
        }

        // 批量插入选项
        if (!allOptions.isEmpty()) {
            examOptionAnswerService.batchAdd(allOptions);
        }
    }

    /**
     * 查询试卷以及对应的题目
     * @param id
     * @param status
     * @param correction
     * @return
     */
    @Override
    public ExamRecords selectById(Integer id, String status, String correction) {
        ExamRecords examRecords = examRecordsMapper.selectById(id);
        LambdaQueryWrapper<ExamQuestions> examQuestionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(status!=null){
            examQuestionsLambdaQueryWrapper.eq(ExamQuestions::getQuestionType, status);
        }
        examQuestionsLambdaQueryWrapper.eq(ExamQuestions::getExamRecordId,examRecords.getId());
        List<ExamQuestions> examQuestions = examQuestionsService.list(examQuestionsLambdaQueryWrapper);
        examRecords.setList(examQuestions);
        LambdaQueryWrapper<ExamOptionAnswer> examOptionAnswerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        for (ExamQuestions examQuestion : examQuestions) {
            examOptionAnswerLambdaQueryWrapper.eq(ExamOptionAnswer::getQuestionId, examQuestion.getId());
            List<ExamOptionAnswer> examOptionAnswers = examOptionAnswerService.list(examOptionAnswerLambdaQueryWrapper);
            if (correction != null){
                examOptionAnswers= examOptionAnswers.stream().filter(option -> option.getIsCorrect() == 1).toList();
            }
            examQuestion.setOptions(examOptionAnswers);
        }
       return examRecords;
    }


    /**
     * 删除
     * @param id
     */
    @Transactional
    @Override
    public void del(Integer id) {
        if(examRecordsMapper.selectById(id) == null) {
            throw new BusinessException("该考试记录不存在");
        }else{
            List<ExamQuestions> list = examQuestionsService.list(new LambdaQueryWrapper<ExamQuestions>().eq(ExamQuestions::getExamRecordId, id));
             for (ExamQuestions examQuestions : list) {
                examOptionAnswerService.remove(new LambdaQueryWrapper<ExamOptionAnswer>().eq(ExamOptionAnswer::getQuestionId, examQuestions.getId()));
             }
             examQuestionsService.remove(new LambdaQueryWrapper<ExamQuestions>().eq(ExamQuestions::getExamRecordId, id));
             examRecordsMapper.deleteById(id);
        }
    }

    /**
     * 修改考试试卷
     */
    @Transactional
    @Override
    public void update(ExamRecords examRecords) {
        ExamRecords selectedById = selectById(examRecords.getId(), null, null);
        if(selectedById != null) {
            examRecords.setUpdateTime(LocalDateTime.now());
            updateById(examRecords);
            if(examRecords.getList().size()==selectedById.getList().size()){
                List<ExamQuestions> list = examRecords.getList();
                for (ExamQuestions examQuestions : list) {
                    examQuestionsService.update(examQuestions);
                    for (ExamOptionAnswer option : examQuestions.getOptions()) {
                        examOptionAnswerService.update(option);
                    }
                }
           }else {
                List<ExamQuestions> list = selectedById.getList();
                for (ExamQuestions examQuestions : list) {
                    examQuestionsService.remove(new LambdaQueryWrapper<ExamQuestions>().eq(ExamQuestions::getExamRecordId, examRecords.getId()));
                    examOptionAnswerService.remove(new LambdaQueryWrapper<ExamOptionAnswer>().eq(ExamOptionAnswer::getQuestionId, examQuestions.getId()));
                }
                List<ExamQuestions> examRecordsList = examRecords.getList();
                for (ExamQuestions examQuestions : examRecordsList) {
                    examQuestionsService.add(examQuestions);
                    List<ExamOptionAnswer> options = examQuestions.getOptions();
                    System.out.println(options);
                    for (ExamOptionAnswer option : options) option.setId(null);
                    examOptionAnswerService.saveBatch(options);
                }
            }
        }else{
            throw new BusinessException("该考试记录不存在");
        }
    }


    /**
     * 定时任务，每分钟查库当前时间之前的都开启
     */
    @Scheduled(fixedRate = 60000)//60秒
    public void checkExamStartTime() {
        LocalDateTime now = LocalDateTime.now();
        //查询开启时间在当前时间之前且状态为0的
        List<ExamRecords> examRecords = examRecordsMapper.selectList(new LambdaQueryWrapper<ExamRecords>().lt(ExamRecords::getExamStartTime, now).eq(ExamRecords::getStatus, 0));

        if(!examRecords.isEmpty()){
            for (ExamRecords exam : examRecords) {
                exam.setStatus(1);
            }
            examRecordsMapper.batchUpdateStatus(examRecords.stream().map(item -> item.getId()).toList(),examRecords.get(0).getStatus());
        }
        // 查询结束时间在当前时间之后的考试记录，将其状态设置为2
        List<ExamRecords> ongoingExams = examRecordsMapper.selectList(
                new LambdaQueryWrapper<ExamRecords>()
                        .le(ExamRecords::getExamEndTime, now)
                        .eq(ExamRecords::getStatus, 1)
        );
        System.out.println(ongoingExams);
        if (!ongoingExams.isEmpty()) {
            for (ExamRecords ongoingExam : ongoingExams) {
                ongoingExam.setStatus(2);
            }
            List<Integer> ids = ongoingExams.stream().map(item -> item.getId()).toList();
            System.out.println(ids+":"+ongoingExams.get(0).getStatus());
            examRecordsMapper.batchUpdateStatus(ids,ongoingExams.get(0).getStatus()); // 批量更新状态
        }

    }

    /**
     * 发布
     * @param id
     * @param status
     */
    @Override
    public void release(Integer id, Integer status) {
        LambdaQueryWrapper<ExamRecords> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamRecords::getId, id);
        ExamRecords serviceOne = examRecordsMapper.selectOne(wrapper);
        if(serviceOne != null){
            LocalDateTime now = LocalDateTime.now();
            serviceOne.setExamStartTime(now);
            serviceOne.setStatus(status);
            serviceOne.setExamEndTime(now.plusMinutes(serviceOne.getDuration()));
            examRecordsMapper.updateById(serviceOne);
        }
    }
}




